<template>
  <div class="register-container">
    <el-card class="register-card">
      <template #header>
        <div class="card-header">
          <h2>用户注册</h2>
        </div>
      </template>
      
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="0"
        @submit.prevent="handleRegister"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            prefix-icon="User"
            placeholder="用户名 (3-20个字符)"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="nickname">
          <el-input
            v-model="registerForm.nickname"
            prefix-icon="Avatar"
            placeholder="昵称 (2-20个字符)"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            prefix-icon="Message"
            placeholder="邮箱"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            prefix-icon="Lock"
            placeholder="密码 (6-20个字符)"
            show-password
          />
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            prefix-icon="Lock"
            placeholder="确认密码"
            show-password
            @keyup.enter="handleRegister"
          />
        </el-form-item>
        
        <el-form-item>
          <div class="terms-container">
            <el-checkbox v-model="agreeTerms">我已阅读并同意</el-checkbox>
            <router-link to="/terms" class="terms-link">服务条款</router-link>
            和
            <router-link to="/privacy" class="terms-link">隐私政策</router-link>
          </div>
        </el-form-item>
        
        <el-button
          type="primary"
          class="register-button"
          :loading="loading"
          :disabled="!agreeTerms"
          @click="handleRegister"
        >
          注册
        </el-button>
        
        <div class="login-link">
          已有账号? <router-link to="/login">立即登录</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'Register',
  setup() {
    const store = useStore()
    const router = useRouter()
    const registerFormRef = ref(null)
    const loading = ref(false)
    const agreeTerms = ref(false)
    
    // 表单数据
    const registerForm = reactive({
      username: '',
      nickname: '',
      email: '',
      password: '',
      confirmPassword: ''
    })
    
    // 表单验证规则
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length < 6 || value.length > 20) {
        callback(new Error('密码长度应在6到20个字符之间'))
      } else {
        callback()
      }
    }
    
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    
    const registerRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度应在3到20个字符之间', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_-]+$/, message: '用户名只能包含字母、数字、下划线和横杠', trigger: 'blur' }
      ],
      nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '昵称长度应在2到20个字符之间', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { validator: validatePassword, trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' }
      ]
    }
    
    // 处理注册
    const handleRegister = () => {
      if (!agreeTerms.value) {
        ElMessage({
          message: '请阅读并同意服务条款和隐私政策',
          type: 'warning'
        })
        return
      }
      
      registerFormRef.value.validate(valid => {
        if (valid) {
          loading.value = true
          
          // 准备注册数据
          const userData = {
            username: registerForm.username,
            nickname: registerForm.nickname,
            email: registerForm.email,
            password: registerForm.password,
            passwordRepeat: registerForm.confirmPassword
          }
          
          store.dispatch('user/register', userData)
            .then(response => {
              console.log('注册响应:', response);
              ElMessage({
                message: '注册成功!',
                type: 'success'
              })
              
              // 注册成功后跳转到登录页
              router.push('/login')
            })
            .catch(error => {
              console.error('注册失败:', error);
              ElMessage({
                message: error.message || '注册失败，请稍后再试',
                type: 'error'
              })
            })
            .finally(() => {
              loading.value = false
            })
        } else {
          return false
        }
      })
    }
    
    return {
      registerFormRef,
      registerForm,
      registerRules,
      loading,
      agreeTerms,
      handleRegister
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 200px);
  padding: 40px 20px;
}

.register-card {
  width: 100%;
  max-width: 400px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.register-button {
  width: 100%;
  margin-top: 20px;
}

.terms-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  font-size: 14px;
  color: #606266;
}

.terms-link {
  color: #409EFF;
  text-decoration: none;
  margin: 0 5px;
}

.login-link {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #606266;
}

.login-link a {
  color: #409EFF;
  text-decoration: none;
}
</style> 